package com.awccis.admin.controller;

import com.awccis.admin.model.adver.AdverBean;
import com.awccis.admin.model.adver.AdverCombineBean;
import com.awccis.admin.model.adver.CurrentLogoPathBean;
import com.awccis.admin.model.adver.LogoBean;
import com.awccis.admin.service.AdverService;
import com.awccis.common.controller.BaseUploadController;
import com.awccis.common.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: txp
 * @date: 2018/5/7 on 下午8:54
 * @since: 1.0
 * @description:
 **/
@Controller
@RequestMapping(value = "/adver")
public class AdverController extends BaseUploadController {

    /**
     * 日志打印对象
     */
    private Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Resource
    AdverService adverService;

    /**
     * 管理员上传广告照片
     * @param request 参数
     * @param multipartFile 文件对象
     * @return {"imgPath": "/WEB-INF/upload/..........."}
     */
    @RequestMapping("/uploadAdverImg")
    public @ResponseBody
    Map uploadAdverImg(HttpServletRequest request, @RequestParam("uploadFile") MultipartFile multipartFile) {
        String fileName = "adverimg";
        Map map = uploadFile(fileName, request, multipartFile);
        String imgPath = "imgPath";
        String adverLogoPath = (String)map.get(imgPath);
        return map;
    }


    /**
     * 更改广告信息
     * @param adverCombineBean <p/>
     * {
     * 	"adverBean":{
     * 		"logoId":1,
     * 		"adverLocation":"江苏省南京市六合区葛塘街道625号",
     * 		"adverStartDate":"2018-05-03",
     * 		"adverEndDate":"2018-06-03"
     * 	},
     * 	"logoBean":{
     * 		"logoName": "南京科技职业学院",
     * 		"logoPath":"/adverimg/201805031245316"
     * 	}
     * }
     *
     * @return  {
     *     "result": true
     * }
     */
    @RequestMapping(value = "/updateAdverInfo", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody Map updateAdverInfo(@RequestBody AdverCombineBean adverCombineBean){
        logger.info("添加广告信息：" + adverCombineBean.toString());
        Map<String, Object> map = new HashMap<>(2);
        AdverBean adverBean = adverCombineBean.getAdverBean();
        LogoBean logoBean = adverCombineBean.getLogoBean();
        if(adverBean != null && logoBean != null){
            try {
                boolean result = adverService.insertAdverInfo(adverCombineBean);
                map.put(Constants.MAP_KEY_RESULT, result);
            } catch (NullPointerException e) {
                logger.warn("添加广告空指针异常：" + e);
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "添加失败！");
            }
        }else{
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "请求值非法");
        }
        return map;
    }

    /**
     * 获取所有广告信息
     * @param hashMap {"AWCCIS_CODE":"1a5da935ac641f2c46d5096f08d0c40b15234072"}
     * @return {
     *     "result": true,
     *     "message": [
     *         {
     *             "adverId": 1,
     *             "logoId": 1,
     *             "adverLocation": "江苏省南京市六合区葛塘街道625号",
     *             "adverStartDate": 1525305600000,
     *             "adverEndDate": 1527984000000,
     *             "logoName": "南京科技",
     *             "logoPath": "/WEB-INFO/upload/adverimg/20081234798323"
     *         }
     *     ]
     * }
     */
    @RequestMapping(value = "/adverInfo",  produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody Map adverInfo(@RequestBody HashMap<String, String> hashMap){
        logger.info("查看广告信息：" + hashMap);
        Map<String, Object> map = new HashMap<>(2);

        String awccisCode = "AWCCIS_CODE";
        if (hashMap.get(awccisCode) == null) {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "请求参数错误!");
        } else {
            if (Constants.AWCCIS_CODE.equals(hashMap.get(awccisCode))) {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, adverService.selectAllAdverInfo());
            } else {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "系统识别码错误!");
            }
        }
        return map;
    }

    /**
     * 更改当前logo的在九宫格中的位置
     * @param hashMap {"array":[{"currentId":1,"currentLogoPath":"xxx"} , {"currentId":2,"currentLogoPath":"xxx"}]}
     * @return
     */
    @RequestMapping(value = "/currentLogoLocation")
    public @ResponseBody Map currentLogoLocation(@RequestBody HashMap<String, List<CurrentLogoPathBean>> hashMap){
        logger.info("更改logo的当前位置：" + hashMap);
        Map map = new HashMap(2);
        String array = "array";
        List<CurrentLogoPathBean> list;
        boolean flag = false;

        if(hashMap.get(array) != null){
            list = hashMap.get(array);
            flag = adverService.updateNowLogoPath(list);
        }
        map.put(Constants.MAP_KEY_RESULT, flag);
        //logger.warn("更改当前logo位置类型转换异常：" + e);
        return map;
    }

    /**
     * 删除广告信息
     * @param hashMap {"adverId": 1, "logoId": 2, "logoName": "/WEB-INF/upload/adverimg/201805031245316"}
     * @return  {
     *     "result": true,
     *     "message": "删除成功！"
     * }
     */
    @RequestMapping(value = "/deleteAdverInfo")
    public @ResponseBody Map deleteAdverInfo(HttpServletRequest request, @RequestBody HashMap<String, Object> hashMap){
        logger.info("删除广告信息：" + hashMap);
        Map<String, Object> map = new HashMap<>(2);

        int adverId;
        int logoId;
        String logoName;
        try {
            adverId = Integer.parseInt(hashMap.get("adverId").toString());
            logoId = Integer.parseInt(hashMap.get("logoId").toString());
            logoName = hashMap.get("logoName").toString();
        } catch (NumberFormatException e) {
            logger.warn("删除广告信息类型转换异常： " + e);
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "1非法请求值！");
            return map;
        }

        String realPath = "/var/tomcat/awccis/upload/" +logoName;
        logger.info("删除广告信息的广告图片位置：" + realPath);
        boolean imgDeleteResult = true;
        //try {
        //    //通过文件名查找到图片
        //    File adverImg = new File(realPath);
        //    if (adverImg.exists()){
        //        imgDeleteResult = adverImg.delete();
        //    }else{
        //        map.put(Constants.MAP_KEY_RESULT, false);
        //        map.put(Constants.MAP_KEY_MESSAGE, "2请求值非法！");
        //        return map;
        //    }
        //} catch (Exception e) {
        //    map.put(Constants.MAP_KEY_RESULT, false);
        //    map.put(Constants.MAP_KEY_MESSAGE, "文件找不到！");
        //}
        if(imgDeleteResult){
            HashMap<String, Integer> deleteMap = new HashMap<>();
            deleteMap.put("adverId", adverId);
            deleteMap.put("logoId", logoId);
            boolean deleteResult = adverService.deleteAdverInfo(deleteMap);
            if(deleteResult){
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, "删除成功！");
            }else{
                map.put(Constants.MAP_KEY_RESULT, false);
            }
        }else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "文件删除失败！");
        }

        return map;
    }
}
